package com.heima.article.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.IApArticleConfigService;
import com.heima.common.constants.rabbit.RabbitArticleDownOrUpConstants;
import com.heima.model.article.pojos.ApArticleConfig;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.handler.annotation.Payload;

import java.io.IOException;

@Configuration
@Slf4j
public class RabbitArticleDownOrUpListener {

    @Autowired
    private IApArticleConfigService apArticleConfigService;

    @RabbitListener(queuesToDeclare = @Queue(value = RabbitArticleDownOrUpConstants.ARTICLE_DOWN_FOR_CONFIG_QUEUE))
    public void listenerArticleDownForConfigQueue(@Payload String articleId, Message message, Channel channel){
        log.info("APP 端文章下架消息成功投递到消费者，ApArticle id: {}", articleId);
        try {
            apArticleConfigService.update(
                    Wrappers.<ApArticleConfig>lambdaUpdate()
                            .set(ApArticleConfig::getIsDown, true)
                            .eq(ApArticleConfig::getArticleId, articleId)

            );
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("APP 端文章下架处理成功，已返回 ACK 确认");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("APP 端文章下架处理失败，失败原因: {}, APP 端文章 id: {}", e.getMessage(), articleId);
        }
    }

    @RabbitListener(queuesToDeclare = @Queue(value = RabbitArticleDownOrUpConstants.ARTICLE_UP_FOR_CONFIG_QUEUE))
    public void listenerArticleUpForConfigQueue(@Payload String articleId, Message message, Channel channel){
        log.info("APP 端文章上架消息成功投递到消费者，ApArticle id: {}", articleId);
        try {
            apArticleConfigService.update(
                    Wrappers.<ApArticleConfig>lambdaUpdate()
                            .set(ApArticleConfig::getIsDown, false)
                            .eq(ApArticleConfig::getArticleId, articleId)

            );
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("APP 端文章上架处理成功，已返回 ACK 确认");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("APP 端文章上架处理失败，失败原因: {}, APP 端文章 id: {}", e.getMessage(), articleId);
        }
    }

}
